package tool

import (
	"beego/models"
	"beego/redis"
	"encoding/json"
	"fmt"
)

func SetSchedules() {
	//洛杉矶凌晨四点准时刷新赛程
	for {
		redis.Init()
		res, _ := redis.GetRedis("e")
		if res == nil {
			schedules := SendGetRQ("https://china.nba.cn/stats2/season/schedule.json?countryCode=CN&days=7&locale=zh_CN&tz=+8")
			schedulesStruct := *Transfer(schedules)
			data, _ := json.Marshal(schedulesStruct)
			redis.SetRedis(data, "e", 3600*12)
		}
	}
}
func Transfer(schedules []byte) *models.Schedules {
	var gameList []models.Game
	var r interface{}
	err := json.Unmarshal(schedules, &r)
	if err != nil {
		fmt.Println(err)
	}
	gobook, _ := r.(map[string]interface{})
	payload := TansferMapRet(gobook, "payload")
	dates := TansferMapRet(payload, "dates")
	schedulesList := extractList(dates)
	for i := 0; i < len(schedulesList); i++ {
		gameList = append(gameList, *extractGames(schedulesList[i]))
	}
	return &models.Schedules{gameList}
}
func extractGames(a interface{}) *models.Game {
	profile := TansferMapRet(a, "profile")
	homeTeamProfile := TansferMapRet(TansferMapRet(a, "homeTeam"), "profile")
	awayTeamProfile := TansferMapRet(TansferMapRet(a, "awayTeam"), "profile")
	gameId := InterfaceToString(TansferMapRet(profile, "gameId"))
	awayTeamCity := InterfaceToString(TansferMapRet(awayTeamProfile, "city"))
	awayTeamDisplayAbbr := InterfaceToString(TansferMapRet(awayTeamProfile, "displayAbbr"))
	homeTeamCity := InterfaceToString(TansferMapRet(homeTeamProfile, "city"))
	homeTeamDisplayAbbr := InterfaceToString(TansferMapRet(homeTeamProfile, "displayAbbr"))
	awayTeam := models.AwayTeam{DisplayAbbr: awayTeamDisplayAbbr, City: awayTeamCity}
	homeTeam := models.HomeTeam{DisplayAbbr: homeTeamDisplayAbbr, City: homeTeamCity}
	game := models.Game{AwayTeam: awayTeam, HomeTeam: homeTeam, GameId: gameId}
	return &game
}
func extractList(bb interface{}) []interface{} {
	a, _ := bb.([]interface{})
	s := a[0]
	d, _ := s.(map[string]interface{})
	games := TansferMapRet(d, "games")
	f, _ := games.([]interface{})
	return f
}
